package radubrehar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import radubrehar.util.HibernateUtil;

public class LinkManager {
	
	private static final SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
	
	public static List<Link> getAllLinks() {

		Session session = sessionFactory.openSession();
		Transaction tr = session.beginTransaction();
		
		ArrayList<Link> links = (ArrayList<Link>) session.createQuery("from Link").list();
		
		tr.commit();
		return links;
	}
	
	public static Link getLinkWithURL(String URL){
		
		List<Link> links = getAllLinks();
		
		Comparator comp = new LinkComparator();
		Collections.sort(links, comp);
		
		int index = Collections.binarySearch(links, new Link(URL), comp);
		
		if (index >= 0){
			return links.get(index);
		} else {
			return new Link(URL);
		}
		
	}
	
	public static void saveOrUpdate(Link link){
		
		Session session = sessionFactory.openSession();
		Transaction tr = session.beginTransaction();
		
		session.saveOrUpdate(link);
		
		tr.commit();
	}
}

class LinkComparator implements Comparator<Link> {

	@Override
	public int compare(Link o1, Link o2) {
		return o1.getURL().compareTo(o2.getURL());
	}
	
}
